package com.nchu.chatserver.controller;

import com.nchu.chatserver.dao.MessageDTO;
import com.nchu.chatserver.entity.Message;
import com.nchu.chatserver.entity.User;
import com.nchu.chatserver.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 王小航
 * @Date: 2025/05/07/22:01
 * @Description:
 */
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/messages")
public class MessageController {
    @Autowired
    private MessageService messageService;

    @GetMapping("/unread")
    public ResponseEntity<List<Message>> getUnreadMessages(@RequestParam Integer userId) {
        return ResponseEntity.ok(messageService.getUnreadMessages(userId));
    }

    @GetMapping("/getAllMessages")
    public ResponseEntity<List<Message>> getAllMessages(@RequestParam Integer userId,@RequestParam Integer contactId) {
        return ResponseEntity.ok(messageService.getAllMessages(userId,contactId));
    }


    // 新增发送消息的接口
    @PostMapping("/send")
    public ResponseEntity<Message> sendMessage(@RequestBody MessageDTO newMessage) {
        try {
            // 调用服务层保存消息
            Message savedMessage = messageService.sendMessage(newMessage);
            return ResponseEntity.ok(savedMessage);
        } catch (Exception e) {
            // 如果发生错误，返回错误信息
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }

    // 新增标记消息为已读的接口
    @PostMapping("/markAsRead")
    public ResponseEntity<String> markMessagesAsRead(@RequestParam Integer userId,@RequestParam Integer contactId) {
        try {
            messageService.markMessagesAsRead(userId, contactId);
            return ResponseEntity.ok("消息已成功标记为已读");
        } catch (Exception e) {

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("标记消息为已读失败");
        }
    }
}